/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package pgentity;

import db.DBContext;
import db.PGKeys;
import db.RedisKey;
import java.util.HashMap;
import java.util.Map;
import share.PGError;
import share.PGException;
import share.PGHelper;
import share.PGMacro;

/**
 *
 * @author Salm
 */
public class CoinCard implements PGEntity {
    private final String uid;
    
    private long start;
    private long end;

    public CoinCard(String uid) {
        this.uid = uid;
    }
    
    public static CoinCard getCC(String uid)
    {
        CoinCard cc = new CoinCard(uid);
        cc.updateFromDB();
        
        return cc;
    }
    
    public static RedisKey key(String uid)
    {
        return PGKeys.USERS.getChild(uid)
                .getChild(PGKeys.FD_COINCARD);
    }
    
    public static void destroy(String uid)
    {
        DBContext.Redis().del(key(uid));
    }

    @Override
    public void updateFromDB() {
        Map<String, String> data = DBContext.Redis()
                .hgetall(key(uid));
        
        start = PGHelper.toLong(data.get(PGMacro.CC_START));
        end = PGHelper.toLong(data.get(PGMacro.CC_END));
    }

    @Override
    public void saveToDB() {
        Map<String, String> data = new HashMap(2);
        
        data.put(PGMacro.CC_START, String.valueOf(start));
        data.put(PGMacro.CC_END, String.valueOf(end));
        
        DBContext.Redis().hset(key(uid), data);
    }
    
    public void setDueTime(long start, long end)
    {
        PGException.Assert(end > start, PGError.INVALID_CC,
                "End time must greater than Start time");
        
        this.start = start;
        this.end = end;
    }
    
    public boolean inCC(long now)
    {
        return start <= now && now < end;
    }
    
    public Object buildAMF()
    {
        Map<String, Object> data = new HashMap(2);
        
        data.put(PGMacro.CC_START, start);
        data.put(PGMacro.CC_END, end);
        
        return data;
    }
    
    public Object dump()
    {
        return DBContext.Redis().hgetall(key(uid));
    }
}
